<template>
  <div class="context-menu" v-show="visible" :style="{ left: x + 'px', top: y + 'px' }">
    <ul>
      <li :class="{ disabled: !canCopy }" @click="handleAction('copy')">复制</li>
      <li :class="{ disabled: !canPaste }" @click="handleAction('paste')">粘贴</li>
      <li :class="{ disabled: !canDelete }" @click="handleAction('delete')">删除</li>
      <li :class="{ disabled: !canViewResult }" @click="handleAction('viewResult')">查看运行结果</li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'ContextMenu',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    x: {
      type: Number,
      default: 0
    },
    y: {
      type: Number,
      default: 0
    },
    // 控制菜单项是否可用
    canCopy: {
      type: Boolean,
      default: true
    },
    canPaste: {
      type: Boolean,
      default: true
    },
    canDelete: {
      type: Boolean,
      default: true
    },
    canViewResult: {
      type: Boolean,
      default: true
    }
  },
  methods: {
    handleAction(action) {
      // 如果菜单项被禁用，则不触发事件
      if (
        (action === 'copy' && !this.canCopy) ||
        (action === 'paste' && !this.canPaste) ||
        (action === 'delete' && !this.canDelete) ||
        (action === 'viewResult' && !this.canViewResult)
      ) {
        return;
      }
      
      // 触发对应的事件
      this.$emit(action);
      // 操作后隐藏菜单
      this.$emit('update:visible', false);
    },
    // 点击外部关闭菜单
    closeMenu() {
      this.$emit('update:visible', false);
    }
  },
  mounted() {
    // 添加全局点击事件监听，点击菜单外部时关闭菜单
    document.addEventListener('click', this.closeMenu);
    // 不要在这里监听contextmenu事件，会阻止右键菜单显示
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('click', this.closeMenu);
  }
};
</script>

<style scoped>
.context-menu {
  position: fixed;
  z-index: 1000;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 5px 0;
  min-width: 150px;
}

.context-menu ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

.context-menu li {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
}

.context-menu li:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.context-menu li.disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.context-menu li.disabled:hover {
  background-color: transparent;
  color: #c0c4cc;
}
</style>